﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using System.Security.Cryptography;

namespace FriendlyFireLibrary
{
    public class EncryptedTransfer
    {
        private RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
        private RSAParameters sendInfo;
        private RSAParameters recvInfo;
        public EncryptedTransfer(RSAParameters sendInfo, RSAParameters recvInfo)
        {
            this.sendInfo = sendInfo;
            this.recvInfo = recvInfo;
        }
        public byte[] Encrypt(byte[] data)
        {
            return rsa.Encrypt(data, true);
        }
        public byte[] Decrypt(byte[] data)
        {
            return rsa.Decrypt(data, true);
        }
        public void prepEncrypt()
        {
            rsa.ImportParameters(sendInfo);
        }
        public void prepDecrypt()
        {
            rsa.ImportParameters(recvInfo);
        }
    }
    public class NetworkCodeCommon
    {
        public int size = 1024;
        public int maxReceive = 0;
        public int maxSend = 0;
        public bool paused = false;
        TextBox output;
        ProgressBar pgBar;
        ListBox lsbClients;

        public NetworkCodeCommon(TextBox output, ProgressBar pgBar, ListBox lsbClients)
        {
            this.output = output;
            this.pgBar = pgBar;
            this.lsbClients = lsbClients;
        }
        public delegate void DataReceived(byte[] data, int dataType);
        public void ReceiveData(DataReceived method, Socket server)
        {
            byte[] data;

            byte[] initialData = new byte[8];
            int recv = server.Receive(initialData, 0, 8, SocketFlags.None);
            long totalSize = BitConverter.ToInt64(initialData, 0);

            initialData = new byte[4];
            recv = server.Receive(initialData, 0, 4, SocketFlags.None);
            int dataType = BitConverter.ToInt32(initialData, 0);

            data = new byte[totalSize];

            long sizeReceived = 0;
            byte[] tdata = new byte[size];
            int pos = 0;
            while (sizeReceived < totalSize)
            {
                recv = server.Receive(tdata);
                sizeReceived += recv;
                for (int i = 0; i < recv; i++, pos++)
                    data[pos] = tdata[i];
            }

            method(data, dataType);
        }
        public void SendTheData(byte[] data, Socket client, int dataType)
        {
            //Send Data Size
            byte[] initialData = new byte[8];
            long totalSize = data.Length;
            initialData = BitConverter.GetBytes(totalSize);
            client.Send(initialData, initialData.Length, SocketFlags.None);

            //Send Data Type
            initialData = new byte[4];
            initialData = BitConverter.GetBytes(dataType);
            client.Send(initialData, initialData.Length, SocketFlags.None);

            long sent = 0;
            while (sent < totalSize)
            {
                byte[] tdata = new byte[size];
                int i = size;
                for (int j = 0; j < size; j++, sent++)
                    if (sent < totalSize)
                        tdata[j] = data[sent];
                    else
                    {
                        i = j;
                        break;
                    }
                client.Send(data, i, SocketFlags.None);
            }
        }
        public void SendTheFile(string sendFile, Socket client)
        {
            FileStream stream = File.Open(sendFile, FileMode.Open);

            //Send File Size
            byte[] initialData = new byte[8];
            long totalSize = stream.Length;
            initialData = BitConverter.GetBytes(totalSize);
            client.Send(initialData, initialData.Length, SocketFlags.None);

            //Send File Name Size
            string fileName = Path.GetFileName(sendFile);
            byte[] filenameSize = new byte[4];
            int fnSize = fileName.Length;
            filenameSize = BitConverter.GetBytes(fnSize);
            client.Send(filenameSize, filenameSize.Length, SocketFlags.None);

            byte[] fileData = new byte[fnSize];
            fileData = Encoding.ASCII.GetBytes(fileName);
            client.Send(fileData, 0, fnSize, SocketFlags.None);

            long sent = 0;
            while (sent < totalSize)
            {
                byte[] data = new byte[1024];
                int i = 1024;
                for (int j = 0; j < 1024; j++)
                    if (stream.CanRead)
                        data[j] = (byte)stream.ReadByte();
                    else
                    {
                        i = j;
                        break;
                    }
                //data = Encrypt(data);
                while (paused)
                {
                    Thread.Sleep(10);
                }
                client.Send(data, i, SocketFlags.None);
                sent += 1024;
                Thread.Sleep(maxSend);
            }
            stream.Close();
        }
        public string ReceiveFile(string directory, Socket server)
        {
            byte[] initialData = new byte[8];
            int recv = server.Receive(initialData, 0, 8, SocketFlags.None);
            long totalSize = BitConverter.ToInt64(initialData, 0);

            byte[] fileNameSize = new byte[4];
            recv = server.Receive(fileNameSize, 0, 4, SocketFlags.None);
            int fileSizeName = BitConverter.ToInt32(fileNameSize, 0);

            byte[] fileName = new byte[fileSizeName];
            recv = server.Receive(fileName, SocketFlags.None);
            string name = Encoding.ASCII.GetString(fileName, 0, fileSizeName);


            AddText("Receiving File : " + name);

            int currProg = 0;
            int maxPerc = (int)(totalSize / 1024);
            SetMaxPerc(maxPerc);
            SetPercentage(currProg);
            long sizeReceived = 0;
            byte[] data = new byte[1024];
            FileStream stream = File.Create(directory + @"\" + name);
            while (sizeReceived < totalSize)
            {
                recv = server.Receive(data);
                sizeReceived += recv;
                if (stream.CanWrite)
                    stream.Write(data, 0, recv);
                currProg++;
                if (currProg < maxPerc)
                    SetPercentage(currProg);
                while (paused)
                {
                    Thread.Sleep(10);
                }
                Thread.Sleep(maxReceive);
            }
            stream.Close();
            return name;
        }
        public string ReceiveString(Socket client)
        {
            byte[] fileNameSize = new byte[size];
            int recv = client.Receive(fileNameSize, 0, size, SocketFlags.None);
            return Encoding.ASCII.GetString(fileNameSize, 0, recv);
        }

        private delegate void AddTextDelegate(object item);
        private delegate void AddListBoxItemDelegate(object item);
        private delegate void ClearListBoxDelegate();
        private delegate void SetPercentageDelegate(object item);
        private delegate void SetMaxPercDelegate(object item);
        public void AddText(object item)
        {
            if(output != null)
            if (this.output.InvokeRequired)
            {
                this.output.Invoke(new AddTextDelegate(this.AddText), item);
            }
            else
            {
                this.output.Text += item.ToString() + Environment.NewLine;
            }
        }
        public void AddListBoxItemText(object item)
        {
            if (lsbClients != null)
                if (this.lsbClients.InvokeRequired)
                {
                    this.lsbClients.Invoke(new AddListBoxItemDelegate(this.AddListBoxItemText), item);
                }
                else
                {
                    this.lsbClients.Items.Add(item.ToString());
                }
        }
        public void ClearListBox()
        {
            if (lsbClients != null)
                if (this.lsbClients.InvokeRequired)
                {
                    this.lsbClients.Invoke(new ClearListBoxDelegate(this.ClearListBox));
                }
                else
                {
                    this.lsbClients.Items.Clear();
                }
        }
        public void SetPercentage(object item)
        {
            if (pgBar != null)
            if (this.pgBar.InvokeRequired)
            {
                this.pgBar.Invoke(new SetPercentageDelegate(this.SetPercentage), item);
            }
            else
            {
                this.pgBar.Value = (int)item;
            }
        }
        public void SetMaxPerc(object item)
        {
            if (pgBar != null)
            if (this.pgBar.InvokeRequired)
            {
                this.pgBar.Invoke(new SetPercentageDelegate(this.SetMaxPerc), item);
            }
            else
            {
                this.pgBar.Maximum = (int)item;
            }
        }
    }
    public class NetworkAsyncCodeServer
    {
        Socket server;
        NetworkCodeCommon cmn;
        public List<Socket> clients = new List<Socket>();
        public List<string> clientsNames = new List<string>();
        private byte[] data = new byte[1024];
        string theFilename = "", theMessage, directory = @"C:\";
        NetworkCodeCommon.DataReceived receivedDataMethod;
        byte[] sendingData;
        int sendingDataType;

        public NetworkAsyncCodeServer(NetworkCodeCommon.DataReceived receivedData, TextBox output, ListBox lsbClients)
        {
            cmn = new NetworkCodeCommon(output, null, lsbClients);
            receivedDataMethod = receivedData;
            StartServerSocket();
        }
        public NetworkAsyncCodeServer(NetworkCodeCommon.DataRecieved recieveData, TextBox output, ListBox lsbClients, NetworkCodeCommon.)
        private void StartServerSocket()
        {
            cmn.AddText("Server Starting...");
            server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050);
            server.Bind(iep);
            server.Listen(5);
            server.BeginAccept(new AsyncCallback(AcceptConn), server);
            cmn.AddText("Server Started...");
        }

        void AcceptConn(IAsyncResult iar)
        {
            Socket client;
            Socket oldserver = (Socket)iar.AsyncState;
            client = oldserver.EndAccept(iar);

            

            byte[] clientNameSize = new byte[4];
            int recv = client.Receive(clientNameSize, 0, 4, SocketFlags.None);
            int clientSizeName = BitConverter.ToInt32(clientNameSize, 0);

            byte[] clientName = new byte[clientSizeName];
            recv = client.Receive(clientName, SocketFlags.None);
            string name = Encoding.ASCII.GetString(clientName, 0, clientSizeName);
            cmn.AddText("Client Connected : " + name);
            cmn.AddText("Connected From : " + client.RemoteEndPoint.ToString());
            cmn.AddListBoxItemText(name);
            clients.Add(client);
            clientsNames.Add(name);
            SendMessage("Welcome to my server.", client);

            client.BeginReceive(data, 0, cmn.size, SocketFlags.None,
                  new AsyncCallback(ReceiveData), client);
            server.BeginAccept(new AsyncCallback(AcceptConn), server);

        }
        void SendData(IAsyncResult iar)
        {
            Socket client = (Socket)iar.AsyncState;
            int sent = client.EndSend(iar);
            client.BeginReceive(data, 0, cmn.size, SocketFlags.None,
                  new AsyncCallback(ReceiveData), client);
        }
        void SendMessageAsync(IAsyncResult iar)
        {
            Socket client = (Socket)iar.AsyncState;
            int sent = client.EndSend(iar);
            byte[] msg = Encoding.ASCII.GetBytes(theMessage);
            client.Send(msg, 0, msg.Length, SocketFlags.None);
            //client.BeginReceive(data, 0, cmn.size, SocketFlags.None,
                  //new AsyncCallback(ReceiveData), client);
        }
        void SendFileAsync(IAsyncResult iar)
        {
            Socket client = (Socket)iar.AsyncState;
            int sent = client.EndSend(iar);
            cmn.SendTheFile(theFilename, client);
            cmn.AddText("Sent File : " + theFilename);
            client.BeginReceive(data, 0, cmn.size, SocketFlags.None,
                  new AsyncCallback(ReceiveData), client);
        }
        void DataAsync(IAsyncResult iar)
        {
            Socket client = (Socket)iar.AsyncState;
            int sent = client.EndSend(iar);
            cmn.SendTheData(sendingData, client, sendingDataType);
            cmn.AddText("Sent Data of Type : " + sendingDataType);
            client.BeginReceive(data, 0, cmn.size, SocketFlags.None,
                  new AsyncCallback(ReceiveData), client);
        }
        void RequestFileAsync(IAsyncResult iar)
        {
            Socket client = (Socket)iar.AsyncState;
            int sent = client.EndSend(iar);

            string fileName = theFilename;
            byte[] filenameSize = new byte[4];
            int fnSize = fileName.Length;
            filenameSize = BitConverter.GetBytes(fnSize);
            client.Send(filenameSize, filenameSize.Length, SocketFlags.None);

            byte[] fileData = new byte[fnSize];
            fileData = Encoding.ASCII.GetBytes(fileName);
            client.Send(fileData, 0, fnSize, SocketFlags.None);
        }
        void ReceiveData(IAsyncResult iar)
        {
            Socket client = (Socket)iar.AsyncState;
            if (client.Connected)
            {
                int recv = client.EndReceive(iar);
                string receivedData = Encoding.ASCII.GetString(data, 0, recv);

                #region Message
                if (receivedData == "Message")
                {
                    cmn.AddText(cmn.ReceiveString(client));
                    client.BeginReceive(data, 0, cmn.size, SocketFlags.None, new AsyncCallback(ReceiveData), client);
                }
                #endregion
                #region File
                else if (receivedData == "File")
                {
                    cmn.AddText("Received : " + cmn.ReceiveFile(directory, client));
                    client.BeginReceive(data, 0, cmn.size, SocketFlags.None, new AsyncCallback(ReceiveData), client);
                }
                #endregion
                #region Data
                else if (receivedData == "Data")
                {
                    cmn.ReceiveData(receivedDataMethod, client);
                    client.BeginReceive(data, 0, cmn.size, SocketFlags.None, new AsyncCallback(ReceiveData), client);
                }
                #endregion
                #region RequestFile
                else if (receivedData == "RequestFile")
                {
                    byte[] fileNameSize = new byte[4];
                    recv = client.Receive(fileNameSize, 0, 4, SocketFlags.None);
                    int fileSizeName = BitConverter.ToInt32(fileNameSize, 0);

                    byte[] fileName = new byte[fileSizeName];
                    recv = client.Receive(fileName, SocketFlags.None);
                    string name = Encoding.ASCII.GetString(fileName, 0, fileSizeName);

                    SendFile(name, client);
                }
                #endregion
                #region DisconnectingClient
                else if (receivedData == "Disconnecting")
                {
                    int i = -1;
                    for (int j = 0; j < clients.Count; j++)
                        if (client == clients[j])
                            i = j;
                    if (i != -1)
                    {
                        cmn.AddText("Client Disconnected : " + clientsNames[i]);
                        cmn.AddText("Disconnected From : " + clients[i].RemoteEndPoint.ToString());
                        clients.RemoveAt(i);
                        clientsNames.RemoveAt(i);
                    }
                    client.Disconnect(false);
                    cmn.ClearListBox();
                    for (int j = 0; j < clientsNames.Count; j++)
                        cmn.AddListBoxItemText(clientsNames[j]);
                }
                #endregion
                #region NOCOMMAND
                else
                {
                    client.BeginReceive(data, 0, cmn.size, SocketFlags.None, new AsyncCallback(ReceiveData), client);
                }
                #endregion
            }
        }
        void ReceiveMessage(IAsyncResult iar)
        {
            Socket client = (Socket)iar.AsyncState;
            int recv = client.EndReceive(iar);
            string stringData = Encoding.ASCII.GetString(data, 0, recv);
            cmn.AddText(stringData);
            client.BeginReceive(data, 0, cmn.size, SocketFlags.None, new AsyncCallback(ReceiveData), client);
        }

        public void SendFile(string filename, Socket client)
        {
            theFilename = filename;
            cmn.AddText("Sending File : " + filename);
            byte[] msg = Encoding.ASCII.GetBytes("File");
            client.BeginSend(msg, 0, msg.Length, SocketFlags.None,
                   new AsyncCallback(SendFileAsync), client);
        }
        public void SendMessage(string message, Socket client)
        {
            theMessage = "Server : " + message;
            byte[] msg = Encoding.ASCII.GetBytes("Message");
            client.BeginSend(msg, 0, msg.Length, SocketFlags.None,
                   new AsyncCallback(SendMessageAsync), client);
        }
        public void RequestFile(string file, Socket client)
        {
            theFilename = file;
            byte[] msg = Encoding.ASCII.GetBytes("RequestFile");
            client.BeginSend(msg, 0, msg.Length, SocketFlags.None,
                   new AsyncCallback(RequestFileAsync), client);
        }
        public void RequestFileID(long ID, Socket client)
        {
            theFilename = ""; //Get filename from the database of the client
            byte[] msg = Encoding.ASCII.GetBytes("RequestFile");
            client.BeginSend(msg, 0, msg.Length, SocketFlags.None,
                   new AsyncCallback(RequestFileAsync), client);
        }
        public void SendData(byte[] data, int dataType, Socket client)
        {
            sendingData = data;
            sendingDataType = dataType;
            byte[] msg = Encoding.ASCII.GetBytes("Data");
            client.BeginSend(msg, 0, msg.Length, SocketFlags.None,
                   new AsyncCallback(DataAsync), client);
        }
        public void Shutdown()
        {
            byte[] message = Encoding.ASCII.GetBytes("Quit");
            for (int i = 0; i < clients.Count; i++)
            {
                clients[i].BeginSend(message, 0, message.Length, SocketFlags.None, null, clients[i]);
                clients[i].Disconnect(false);
                clients[i].Close();
            }
            clients.Clear();
            server.Disconnect(false);
            cmn.AddText("Server Shutdown. All clients disconnected.");
        }

        public void SetDir(string dir)
        {
            directory = dir;
        }
        public void Pause(bool pause)
        {
            cmn.paused = pause;
            if(pause)
                cmn.AddText("Paused Transfers");
            else
                cmn.AddText("Resumed Transfers");
        }
        public void SetMaxSend(int kb)
        {
            if (kb > 0)
                cmn.maxSend = (1000 / kb);
            else if (kb == 0)
                cmn.maxSend = 0;
        }
        public void SetMaxRecv(int kb)
        {
            if (kb > 0)
                cmn.maxReceive = (1000 / kb);
            else if (kb == 0)
                cmn.maxReceive = 0;
        }
    }
    public class NetworkAsyncCodeClient
    {
        NetworkCodeCommon cmn;
        Socket client;
        public bool connected = false;
        public bool hostnameResolved = true;
        private byte[] data = new byte[1024];
        string clientName = "", theFilename = "", directory = @"C:\", theMessage = "";
        NetworkCodeCommon.DataReceived receivedDataMethod;
        byte[] sendingData;
        int sendingDataType;

        public NetworkAsyncCodeClient(string IP, NetworkCodeCommon.DataReceived receivedData, TextBox output, ProgressBar pgBar, string clientName)
        {
            bool test = false;
            for (int i = 0; i < IP.Length; i++)
                if (IP[i] != '.')
                    if (Char.IsLetter(IP[i]))
                        test = true;
            if (test)
                try
                {
                    StartClientSocket(Dns.GetHostEntry(IP).AddressList[0].ToString());
                    hostnameResolved = true;
                }
                catch
                {
                    hostnameResolved = false;
                }
            else
            {
                StartClientSocket(IP);
                hostnameResolved = true;
            }
            cmn = new NetworkCodeCommon(output, pgBar, null);
            receivedDataMethod = receivedData;
            this.clientName = clientName;
        }
        private void StartClientSocket(string IP)
        {
            Socket newsock = new Socket(AddressFamily.InterNetwork,
                       SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint iep = new IPEndPoint(IPAddress.Parse(IP), 9050);
            newsock.BeginConnect(iep, new AsyncCallback(Connected), newsock);
        }

        void Connected(IAsyncResult iar)
        {
            client = (Socket)iar.AsyncState;
            try
            {
                client.EndConnect(iar);

                //Send File Name Size
                byte[] clientnameSize = new byte[4];
                int fnSize = clientName.Length;
                clientnameSize = BitConverter.GetBytes(fnSize);
                client.Send(clientnameSize, clientnameSize.Length, SocketFlags.None);

                byte[] fileData = new byte[fnSize];
                fileData = Encoding.ASCII.GetBytes(clientName);
                client.Send(fileData, 0, fnSize, SocketFlags.None);
                connected = true;
                client.BeginReceive(data, 0, cmn.size, SocketFlags.None,
                       new AsyncCallback(ReceiveData), client);
            }
            catch (SocketException)
            {
            }
        }
        void ReceiveData(IAsyncResult iar)
        {
            Socket client = (Socket)iar.AsyncState;
            if (client.Connected)
            {
                int recv = client.EndReceive(iar);
                string receivedData = Encoding.ASCII.GetString(data, 0, recv);

                #region Message
                if (receivedData == "Message")
                {
                    cmn.AddText(cmn.ReceiveString(client));
                    client.BeginReceive(data, 0, cmn.size, SocketFlags.None, new AsyncCallback(ReceiveData), client);
                }
                #endregion
                #region File
                else if (receivedData == "File")
                {
                    cmn.AddText("Received : " + cmn.ReceiveFile(directory, client));
                    client.BeginReceive(data, 0, cmn.size, SocketFlags.None, new AsyncCallback(ReceiveData), client);
                }
                #endregion
                #region Data
                else if (receivedData == "Data")
                {
                    cmn.ReceiveData(receivedDataMethod, client);
                    client.BeginReceive(data, 0, cmn.size, SocketFlags.None, new AsyncCallback(ReceiveData), client);
                }
                #endregion
                #region RequestFile
                else if (receivedData == "RequestFile")
                {
                    byte[] fileNameSize = new byte[4];
                    recv = client.Receive(fileNameSize, 0, 4, SocketFlags.None);
                    int fileSizeName = BitConverter.ToInt32(fileNameSize, 0);

                    byte[] fileName = new byte[fileSizeName];
                    recv = client.Receive(fileName, SocketFlags.None);
                    string name = Encoding.ASCII.GetString(fileName, 0, fileSizeName);

                    SendFile(name);
                }
                #endregion
                else if (receivedData == "Quit")
                {
                    Shutdown();
                }
                #region NOCOMMAND
                else
                {
                    client.BeginReceive(data, 0, cmn.size, SocketFlags.None, new AsyncCallback(ReceiveData), client);
                }
                #endregion
            }
        }
        void ReceiveMessageData(IAsyncResult iar)
        {
            Socket remote = (Socket)iar.AsyncState;
            int recv = remote.EndReceive(iar);
            string stringData = Encoding.ASCII.GetString(data, 0, recv);
            cmn.AddText(stringData);
            remote.BeginReceive(data, 0, cmn.size, SocketFlags.None, new AsyncCallback(ReceiveData), remote);
        }
        void SendData(IAsyncResult iar)
        {
            Socket remote = (Socket)iar.AsyncState;
            int sent = remote.EndSend(iar);
            remote.BeginReceive(data, 0, cmn.size, SocketFlags.None,
                   new AsyncCallback(ReceiveData), remote);
        }
        void SendFileAsync(IAsyncResult iar)
        {
            Socket client = (Socket)iar.AsyncState;
            int sent = client.EndSend(iar);
            cmn.SendTheFile(theFilename, client);
            cmn.AddText("Sent File : " + theFilename);
            client.BeginReceive(data, 0, cmn.size, SocketFlags.None,
                  new AsyncCallback(ReceiveData), client);
        }
        void RequestFileAsync(IAsyncResult iar)
        {
            Socket client = (Socket)iar.AsyncState;
            int sent = client.EndSend(iar);

            string fileName = theFilename;
            byte[] filenameSize = new byte[4];
            int fnSize = fileName.Length;
            filenameSize = BitConverter.GetBytes(fnSize);
            client.Send(filenameSize, filenameSize.Length, SocketFlags.None);

            byte[] fileData = new byte[fnSize];
            fileData = Encoding.ASCII.GetBytes(fileName);
            client.Send(fileData, 0, fileData.Length, SocketFlags.None);
        }
        void SendMessageAsync(IAsyncResult iar)
        {
            Socket client = (Socket)iar.AsyncState;
            int sent = client.EndSend(iar);
            byte[] msg = Encoding.ASCII.GetBytes(theMessage);
            client.Send(msg, 0, msg.Length, SocketFlags.None);
        }
        void DataAsync(IAsyncResult iar)
        {
            Socket client = (Socket)iar.AsyncState;
            int sent = client.EndSend(iar);
            cmn.SendTheData(sendingData, client, sendingDataType);
            cmn.AddText("Sent Data of Type : " + sendingDataType);
            client.BeginReceive(data, 0, cmn.size, SocketFlags.None,
                  new AsyncCallback(ReceiveData), client);
        }

        public void SendFile(string filename)
        {
            theFilename = filename;
            cmn.AddText("Sending File : " + filename);
            byte[] msg = Encoding.ASCII.GetBytes("File");
            client.BeginSend(msg, 0, msg.Length, SocketFlags.None,
                   new AsyncCallback(SendFileAsync), client);
        }
        public void SendMessage(string message)
        {
            theMessage = "Client : " + message;
            byte[] msg = Encoding.ASCII.GetBytes("Message");
            client.BeginSend(msg, 0, msg.Length, SocketFlags.None,
                   new AsyncCallback(SendMessageAsync), client);
        }
        public void SendMessage(string message, string ClientName)
        {
            theMessage = ClientName + " : " + message;
            byte[] msg = Encoding.ASCII.GetBytes("Message");
            client.BeginSend(msg, 0, msg.Length, SocketFlags.None,
                   new AsyncCallback(SendMessageAsync), client);
        }
        public void RequestFile(string file)
        {
            theFilename = file;
            byte[] msg = Encoding.ASCII.GetBytes("RequestFile");
            client.BeginSend(msg, 0, msg.Length, SocketFlags.None,
                   new AsyncCallback(RequestFileAsync), client);
        }
        public void SendData(byte[] data, int dataType)
        {
            sendingData = data;
            sendingDataType = dataType;
            byte[] msg = Encoding.ASCII.GetBytes("Data");
            client.BeginSend(msg, 0, msg.Length, SocketFlags.None,
                   new AsyncCallback(DataAsync), client);
        }
        public bool Shutdown()
        {
            if (client != null)
            {
                byte[] fileData = new byte[cmn.size];
                fileData = Encoding.ASCII.GetBytes("Disconnecting");
                client.Send(fileData, 0, fileData.Length, SocketFlags.None);

                client.Disconnect(false);
                client.Close();
            }
                return true;
            //cmn.AddText("Client Disconnected.");
        }

        public void SetDir(string dir)
        {
            directory = dir;
        }
        public void Pause(bool pause)
        {
            cmn.paused = pause;
            if (pause)
                cmn.AddText("Paused Transfers");
            else
                cmn.AddText("Resumed Transfers");
        }
        public void SetMaxSend(int kb)
        {
            if (kb > 0)
                cmn.maxSend = (1000 / kb);
            else if (kb == 0)
                cmn.maxSend = 0;
        }
        public void SetMaxRecv(int kb)
        {
            if (kb > 0)
                cmn.maxReceive = (1000 / kb);
            else if (kb == 0)
                cmn.maxReceive = 0;
        }
    }
}
